<?php
require_once 'util/class.dbservice.php';

class SessionDao {
	
	 public function addSessionItem($userId, $skeyMd5, $refreshTime) {
	 	try {
			$collection = $this->getCollection();
			if(!$collection)
				return;

			$collection->insert(array('_id'=>$userId, 'skey'=>$skeyMd5, 
					'refreshTime'=>$refreshTime, 'expireTime'=>$refreshTime+3600));
		} catch(Exception $e) {
			syslog(LOG_ERR, "SessionDao.addSessionItem error, reason=".$e);
		}
	 }
	 
	 public function updateSession($userId, $refreshTime, $skey=null) {
	 	try {
	 		$collection = $this->getCollection();
	 		if(!$collection)
	 			return;
	 		
	 		$updateValues = array('refreshTime'=>$refreshTime, 'expireTime'=>$refreshTime+3600);
	 		if($skey!=null && strlen($skey)!=0) {
	 			$updateValues['skey']=$skey;
	 		}
	 		$collection->update(array('_id'=>$userId), array('$set'=>$updateValues), 
	 				array('upsert'=>true));
	 	} catch(Exception $e) {
	 		syslog(LOG_ERR, "SessionDao.addSessionItem error, reason=".$e);
	 	}
	 }
	 
	 public function removeSessionItem($userId) {
	 	try {
	 		$collection = $this->getCollection();
	 		if(!$collection)
	 			return;
	 	
	 		$collection->remove(array('_id'=>$userId));
	 	} catch(Exception $e) {
	 		syslog(LOG_ERR, "SessionDao.removeSessionItem error, reason=".$e);
	 	}
	 }
	 
	 public function getSessionItem($userId) {
	 	try {
	 		$collection = $this->getCollection();
	 		if(!$collection)
	 			return;
	 	
	 		return $collection->findOne(array('_id'=>$userId));
	 	} catch(Exception $e) {
	 		syslog(LOG_ERR, "SessionDao.getSessionItem error, reason=".$e);
	 		return null;
	 	}
	 }
	 
	 private function getCollection() {
	 	$db=DBService::getGlobalDb();
	 	return $db->session;
	 }
}